<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_m extends CI_Model{
	
	public function __construct(){
		parent::__construct();	
		$this->load->database();
	}


//============================================================================================权限检查开始
	/**
	* 用户登录检验
	* @公共 访问
	* @参数 字符串 $username
	* @参数 字符串 $password
 	* @返回 1:用户名或密码错误 2:账户被停用 3：没有为用户指定角色 100:登录成功
 	*/
	/*
	function validateUser($username, $password){
	
		$sql = "SELECT * FROM (`yj_users`) WHERE (`user_name` = ? OR `user_aliases` = ?) AND (`user_pass` = ? OR `user_pass` = ?)"; 
		$query = $this->db->query($sql, array($username, $username, $password, md5($password))); 
		
		//$this->db->where('user_name', $username);
		//$this->db->or_where('user_aliases', $username);
		//$this->db->where('user_pass', $password);
		//$this->db->or_where('user_pass', md5($password)); 
		//$query = $this->db->get('user');
		//echo $this->db->last_query();//输出随后一次查询的语句
		if($query->num_rows() == 0){
			return 1;
		}else{
			$user = $query->first_row();
			if($user->user_disable == false){
				return 2;
			}else{
				//取角色名称
				$this->db->where('role_id', $user->role_id);
				$query2 = $this->db->get('role');
				
				//取部门名称
				$this->db->where('dept_id', $user->dept_id);
				$query3 = $this->db->get('dept');
				
				if($query2->num_rows() == 0){
					return 3;
				}else{
					//echo $this->db->last_query();//输出随后一次查询的语句
					$user_role = $query2->first_row();
					$user_dept = $query3->first_row();
					$user_info = array(
						'user_id'=>$user->user_id,
						'user_name'=>$user->user_name,
						'role_id'=>$user_role->role_id,
						'role_name'=>$user_role->role_name,
						'dept_id'=>$user_dept->dept_id,
						'dept_name'=>$user_dept->dept_name
					);	
					$this->user_auth->set_user_session($user_info);
					return 100;
				}
			}
		}
	}
	*/
	/**
	 * 取得当前用户能够访问的菜单数组
	 * @参数 字符串 $username 用户名
	 * @返回 二维数组 或 false
 	 */
	function get_user_sub_menu_by_username($username){
		if($username == 'admin'){
			$sql = "select * from yj_menu where menu_level != 0 and menu_level != 3";//超找menu.*表的所有列
		}else{
			$sql = "select yj_menu.* from yj_users, yj_role, yj_role_privilege, yj_privilege, yj_menu
					where yj_users.user_name= ? and 
					yj_users.role_id = yj_role.role_id and 
					yj_role.role_id = yj_role_privilege.role_id and 
					yj_role_privilege.privilege_id = yj_privilege.privilege_id and 
					yj_privilege.menu_id = yj_menu.menu_id and yj_menu.menu_level != 0 and menu_level != 3 order by yj_menu.menu_sort ASC";//超找menu.*表的所有列
		}
		
		$query = $this->db->query($sql, array($username));
		
		if($query->num_rows() > 0){
			foreach($query->result_array() as $menu){
				//if($menu['menu_id'] == 14){//部署时启用该语句屏蔽节点管理功能
				//	continue;
				//}
				$menus[] = array('id' => $menu['menu_id'],
								 'text'=>$menu['menu_title'],
								 'parentId'=>$menu['parent_id'],
								 'sort'=>$menu['menu_sort'],
								 'iconCls'=>$menu['menu_iconCls'],
								 'attributes'=>array('url'=>$menu['menu_url']
							));
			}
			return $menus;
		}else{
			return false;
		}
	}
	
	/**
	 * 检查用户对即将操作的功能是否有操作权限
	 * @参数 字符串 $username 用户名
	 * @参数 字符串 $action 方法
	 * @返回 true or false
 	 */
	function check_user_privilege($username, $action){
		$sql = "select * from yj_users, yj_role, yj_role_privilege, yj_privilege
				where yj_users.user_name = ? and
				yj_users.role_id = yj_role.role_id and
				yj_role.role_id = yj_role_privilege.role_id and
				yj_role_privilege.privilege_id = yj_privilege.privilege_id and
				yj_privilege.action = ?";
		
		$query = $this->db->query($sql, array($username, $action));
		if($query->num_rows() > 0){
			return true;
		}else{
			return false;
		}
	}

//============================================================================================用户管理开始
	function userlist($dept_id = false,$user_id = false){//用户列表
		$this->db->from('users');
 		$this->db->join('role', 'users.role_id = role.role_id','left');
		if($user_id){
			$this->db->where('users.user_id',$user_id); 	
		}
		if($dept_id){
			$this->db->where('users.dept_id',$dept_id); 	
		}
		$this->db->order_by("role.role_sort asc,users.user_sort asc"); 
		$query = $this->db->get();
		return $query->result();
	}
	
	function menuall(){
		$query = $this->db->get('menu');
		//echo $this->db->last_query();//输出随后一次查询的语句
		return $query->result();
	}
	
	//别名检查
	function aliases_check($username,$aliases){
		if(empty($aliases)){
			return false;
		}else{
			$this->db->where('user_name !=', $username);
			$this->db->where('user_aliases', $aliases);
			$query = $this->db->get('users');
			return $query->num_rows() > 0;
		}
	}

	//添加用户
	function useradd($arr){

		$salt = $this->store_salt ? $this->salt() : FALSE;
		$user_pass	= $this->hash_password($arr['user_pass'], $salt);
		$data = array(
			'user_id' => '' ,
			'user_name' => $arr['user_name'],
			'user_actual' => $arr['user_actual'],
			'user_aliases' => $arr['user_aliases'],
			'user_pass' => $user_pass,
			'user_sort' => $arr['user_sort'],
			'role_id' => $arr['role_id'],
			'dept_id' => $arr['dept_id'],
			'active' => (@$arr['user_disable'] == '')?'0':@$arr['user_disable']
		 );				 
		if ($this->store_salt){
			$data['salt'] = $salt;
		}
		return $this->db->insert('users', $data); 

	}
	function useredit($id,$arr){//编辑用户
		$user = $this->get_user($id);
		$user_pass = ($user->user_pass === $arr['user_pass'])?$arr['user_pass']:$this->hash_password($arr['user_pass'], $user->salt);//检查是否修改了密码	
		$data = array(
			'user_actual' => $arr['user_actual'],
			'user_aliases' => $arr['user_aliases'],
			'user_pass' => $user_pass,
			'user_sort' => $arr['user_sort'],
			'role_id' => $arr['role_id'],
			'dept_id' => $arr['dept_id'],
			'active' => $arr['user_disable']
		 );
		$this->db->where('user_id', $id);
		$this->db->limit(1);
		return $this->db->update('users', $data); 
	}
	function userdel($id){//删除用户
		$this->db->trans_begin();//开始事务处理
		$tok = strtok($id,",");
		while ($tok !== false){	
			$this->db->where('user_id', $tok);
			$this->db->delete('users');
			$tok = strtok(",");
		}		
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚			
		}else{
			$this->db->trans_commit();//提交成功
			return true;
		}
	}
	
	
//============================================================================================菜单管理开始
	function menulist($menu_id='',$roleprivilege){
		$this->db->select('menu.menu_id, menu.menu_title, menu.menu_level, menu.menu_url, menu.menu_sort, menu.parent_id, menu.menu_iconCls, privilege.privilege_id, privilege.action');
		$this->db->from('menu');
		if($menu_id){
			$this->db->where('menu.menu_id',$menu_id); 	
		}
		$this->db->join('privilege', 'menu.menu_id = privilege.menu_id','left');
		$this->db->order_by("menu.menu_sort", "asc"); 
		$query = $this->db->get();
		//echo $this->db->last_query();//输出随后一次查询的语句
		foreach($query->result_array() as $menu)
		{
			//$menus[] = $menu;	
			
				if (in_array($menu['privilege_id'],$roleprivilege)){
					$privilegemenus[] = array('id' => $menu['menu_id'],'text'=>$menu['menu_title'],'level'=>$menu['menu_level'],'m_action'=>$menu['action'],'priv_id'=>$menu['privilege_id'],'checked'=>'true','parentId'=>$menu['parent_id'],'sort'=>$menu['menu_sort'],'iconCls'=>$menu['menu_iconCls'],'attributes'=>array('url'=>$menu['menu_url']));
				}else{
					$privilegemenus[] = array('id' => $menu['menu_id'],'text'=>$menu['menu_title'],'level'=>$menu['menu_level'],'m_action'=>$menu['action'],'priv_id'=>$menu['privilege_id'],'parentId'=>$menu['parent_id'],'sort'=>$menu['menu_sort'],'iconCls'=>$menu['menu_iconCls'],'attributes'=>array('url'=>$menu['menu_url']));
				}
			
		}
		return $privilegemenus;
	}
	function menuadd($arr){
		$this->db->trans_begin();//开始事务处理
			$data = array(
				'menu_id' => '' ,
				'menu_title' => $arr['menu_title'],
				'menu_level' => $arr['menu_level'],
				'menu_url' => $arr['menu_url'],
				'menu_sort' => $arr['menu_sort'],
				'parent_id' => $arr['parent_id'],
				'menu_iconCls' => $arr['menu_iconCls']
			 );
			$this->db->insert('menu', $data); 
			$menu_id = mysql_insert_id();
			$data = array(
				'privilege_id' => '' ,
				'privilege_title' => $arr['menu_title'],
				'menu_id' => $menu_id,
				'action' => $arr['menu_action']
			 );
			$this->db->insert('privilege', $data); 
			$privilege_id = mysql_insert_id();
			$data = array(
				'role_id' => '1' ,
				'privilege_id' => $privilege_id
			 );
			$this->db->insert('role_privilege', $data); 
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚
			return false;
		}else{
			$this->db->trans_commit();//提交成功
			$inarr['id'] = $menu_id;	
			$inarr['pid'] = $arr['parent_id'];
			return $inarr;
		}//事务结束
	}
	function menuedit($arr,$id){
		$this->db->trans_begin();//开始事务处理
			$data = array(
				'menu_title' => $arr['menu_title'],
				'menu_level' => $arr['menu_level'],
				'menu_url' => $arr['menu_url'],
				'menu_sort' => $arr['menu_sort'],
				'parent_id' => $arr['parent_id'],
				'menu_iconCls' => $arr['menu_iconCls']
			 );
			$this->db->where('menu_id', $id);
			$this->db->limit(1);
			$this->db->update('menu', $data);
			
			$data = array(
				'privilege_title' => $arr['menu_title'],
				'action' => $arr['menu_action']
			 );
			$this->db->where('privilege_id', $arr['priv_id']);
			$this->db->limit(1);
			$this->db->update('privilege', $data); 
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚			
		}else{
			$this->db->trans_commit();//提交成功
			return true;
		}//事务结束
	}
	function menudel($arr){
		$this->db->where('parent_id', $arr['id']);
		$query = $this->db->get('menu');
		if ($query->num_rows() > 0){
			return false;
		}else{
			$this->db->trans_begin();//开始事务处理
				$tables = array('menu', 'privilege');
				$this->db->where('menu_id', $arr['id']);
				$this->db->delete($tables);
				$this->db->where('privilege_id', $arr['priv_id']);
				$this->db->delete('role_privilege');
			if($this->db->trans_status() === FALSE){
				$this->db->trans_rollback();//事件回滚			
			}else{
				$this->db->trans_commit();//提交成功
				return true;
			}//事务结束	
		}
	}


//============================================================================================部门管理开始
	function deptlist($dept_id=''){
		$this->db->select('dept.dept_id, dept.dept_name, dept.dept_sort, dept.parent_id, dept.dept_iconCls');
		$this->db->from('dept');
		if($dept_id){
			$this->db->where('dept.dept_id',$dept_id); 	
		}		
		$this->db->order_by("dept.dept_sort", "asc"); 
		$query = $this->db->get();
		//echo $this->db->last_query();//输出随后一次查询的语句
		foreach($query->result_array() as $dept)
		{
			$deptarr[] = array('id' => $dept['dept_id'],'text'=>$dept['dept_name'],'parentId'=>$dept['parent_id'],'dept_sort'=>$dept['dept_sort'],'dept_iconCls'=>$dept['dept_iconCls']);
		}
		return $deptarr;
	}
	

	
	function deptadd($arr){
		$data = array(
			'dept_id' => '' ,
			'dept_name' => $arr['dept_name'],
			'dept_sort' => $arr['dept_sort'],
			'parent_id' => $arr['parent_id'],
			'dept_iconCls' => $arr['dept_iconCls']
		 );
		$status = $this->db->insert('dept', $data); 
		if($status){
			$arrs['id'] = $this->db->insert_id();	
			$arrs['pid'] = $arr['parent_id'];
			return $arrs;
		}else{
			return false;	
		}
	}
	function deptedit($arr,$id){
		$data = array(
			'dept_name' => $arr['dept_name'],
			'dept_sort' => $arr['dept_sort'],
			'parent_id' => $arr['parent_id'],
			'dept_iconCls' => $arr['dept_iconCls'],
		 );
		$this->db->where('dept_id', $id);
		$this->db->limit(1);
		return $this->db->update('dept', $data);
	}
	
	//查找指定ID的所有子部门ID
	function dept_child($id = 0){
		global $str;
		$query = $this->db->where('parent_id', $id)->get('dept');
		if($query->num_rows() > 0 ){//如果有子类 
			foreach($query->result_array() as $dept){
				$str[] = $dept['dept_id'];
				$this->dept_child($dept['dept_id']);
			}
		}
		return $str;
	}
	
	//删除部门和子部门
	function deptdel($arr){
		$deptid = $this->dept_child($arr['id']);
		$deptid[] = $arr['id'];
		$query = $this->db->where_in('dept_id', $deptid)->get('users');
		if ($query->num_rows() > 0){
			return false;
		}else{
			$this->db->where_in('dept_id', $deptid);
			$this->db->limit(1);
			return $this->db->delete('dept');
		}
	}



//============================================================================================角色管理开始
	function rolelist($role_id=''){//角色列表
		if($role_id){
			$this->db->where('role_id',$role_id); 	
		}
		$this->db->order_by("role_sort", "asc"); 
		$query = $this->db->get('role');
		//echo $this->db->last_query();//输出随后一次查询的语句
		return $query->result();
	}
	function roleadd($arr){//添加角色
		$this->db->where('role_name', $arr['role_name']); 
		$this->db->or_where('role_groupname', $arr['role_groupname']); 
		$query = $this->db->get('role');
		$row = $query->result();
		if(empty($row)){
			$data = array(
                'role_id' => '' ,
                'role_name' => $arr['role_name'],
                'role_groupname' => $arr['role_groupname'],
				'role_sort' => $arr['role_sort']
             );
			return ($this->db->insert('role', $data))?true:false; 
		}else{
			return false;
		}
	}
	function roleedit($id,$arr){//编辑角色
		$data = array(
			'role_name' => $arr['role_name'],
			'role_groupname' => $arr['role_groupname'],
			'role_sort' => $arr['role_sort']
		);
		$this->db->where('role_id', $id);
		$this->db->limit(1);
		return $this->db->update('role', $data); 
	}
	function roledel($id){//删除角色
		$this->db->where('role_id', $id);
		$query = $this->db->get('users');//检查准备删除的角色下是否有用户
		if ($query->num_rows() > 0){
			return false;	
		}else{
			$tables = array('role','role_privilege');
			$this->db->where('role_id', $id);
			$this->db->delete($tables);
			return true;
		}
	}
	
//============================================================================================用户组权利列表
	function roleprivilege($role_id=''){
		$rows = array();
		$this->db->select('privilege_id');
		$this->db->where('role_id',$role_id); 	
		$query = $this->db->get('role_privilege');
		//echo $this->db->last_query();//输出随后一次查询的语句
		//return $query->result_array();
		if ($query->num_rows() > 0){//如果已经有权限数据，则返回相应数组，否则返回空数组
			foreach ($query->result_array() as $row){
				$sql = "select yj_menu.parent_id from yj_role_privilege, yj_privilege, yj_menu
						where yj_role_privilege.role_id = ? and
						yj_privilege.privilege_id = ? and
						yj_privilege.menu_id = yj_menu.parent_id GROUP BY yj_menu.parent_id";
				$query = $this->db->query($sql, array($role_id, $row['privilege_id']));//指向筛查语句，值取出叶子节点，否则树不能识别已勾选的项
				if ($query->num_rows() == 0)
					$rows[] = $row['privilege_id'];
			}
		}
		return $rows;
	}
	function privilegeeditpost($arr){//修改权限
		$this->db->trans_begin();//开始事务处理
			$this->db->where('role_id', $arr['role_id']);
			if($this->db->delete('role_privilege')){
				$tok = strtok($arr['privilege_id'],",");
				while ($tok !== false){	
					$data = array(
						'role_id' => $arr['role_id'] ,
						'privilege_id' => $tok
					 );
					$this->db->insert('role_privilege', $data); 
					$tok = strtok(",");
				}
			}
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚
			return false;			
		}else{
			$this->db->trans_commit();//提交成功
			return true;
		}//事务结束
		
	}
	
//============================================================================================系统设置
	function settings_site($arr = false){
		if(!$arr){
			$query = $this->db->get('site_settings');
			return $query->row(); 
		}else{
			return $this->db->update('site_settings', $arr); 
		}
	}
	
//============================================================================================个人信息
	/* 获得个人用户信息*/
	function get_personal_user_info(){//用户列表
		$this->db->where('user_name',$this->session->userdata('user_name')); 	
		$query = $this->db->get('users');
		return $query->result();
		//echo $this->db->last_query();//输出随后一次查询的语句
	}
	
	/* 设置个人用户信息。先别名检查 */
	function set_personal_user_info($arr){//用户列表
		$username = $this->session->userdata('user_name');

		$data = array(
			   'user_actual' => $arr['personal_user_actual'],
			   'user_aliases' => $arr['personal_user_aliases'],
			   'user_sex' => $arr['personal_user_sex'],
			   'user_birthday' => $arr['personal_user_birthday'],
			   'user_email' => $arr['personal_user_email'],
			   'user_mobile' => $arr['personal_user_mobile'],
			   'user_tel' => $arr['personal_user_tel'],
			   'user_qq' => $arr['personal_user_qq']
			);
		$this->db->where('user_name', $username);
		return $this->db->update('users', $data); 

	}
	
	//修改密码。先验证就密码，成功后继续
	function user_passedit($username, $old, $new){

		$query = $this->db->select('user_pass, salt')
					  ->where('user_name', $username)
					  ->limit(1)
					  ->get('users');
				  
		$result = $query->row();

	    $db_password = $result->user_pass;
	    $old	 = $this->hash_password_db($username, $old);
	    $new	 = $this->hash_password($new, $result->salt);

	    if ($db_password === $old){
	    	//store the new password and reset the remember code so all remembered instances have to re-login
			$data = array(
			    'user_pass' => $new,
				'remember_code' => '',
			    );

			$this->db->update('users', $data, array('user_name' => $username));
			return $this->db->affected_rows() == 1;
	    }else{
			return false;
		}
		
	}
	
	
	//首页显示的一些数据
		/*首页列出三条通知*/
	function getlistdata_main(){ 
		$this->db->limit(3);
		$query=$this->db->get('notify');
		//echo $this->db->last_query();//输出随后一次查询的语
		return $query->result();
	}

}
